package com.example.springsecrity;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.framwork.code.CommanHead;
import com.example.model.ResModel.AccountInfo;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

//过滤器 OncePerRequestFilter会对每次请求都进行过滤
@Slf4j
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        log.info("doFilterInternal");
        //获取token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //  throw new ServletException("token 缺失");
            //放行 让后面的springsecurity拦截器进行拦截
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        String userId = "";
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(userId)) {
            throw new ServletException("redis用户未登录");
        }
        //从redis中获取用户信息
        String redisKey = CommanHead.RedisLoginUer + userId;
//zy
//        LoginUser loginUser = redisCache.getCacheObject(redisKey);
        String redisKeyUser = stringRedisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isEmpty(redisKeyUser)) {
            throw new ServletException("用户未登录");
        }
        LoginUser loginUser = new LoginUser();
        AccountInfo accountInfo = new AccountInfo();
        loginUser = JSONUtil.toBean(redisKeyUser, LoginUser.class);
        accountInfo.setLogonName(loginUser.getUsername());
        loginUser.setUser(accountInfo);
        loginUser.setUsername(loginUser.getUsername());
        loginUser.setPassword(loginUser.getPassword());
        log.info("过滤器中 redis的用户：" + loginUser.toString());
        if (Objects.isNull(loginUser)) {
            throw new ServletException("用户未登录");
        }
        stringRedisTemplate.expire(redisKey, CommanHead.nRedisMin, TimeUnit.MINUTES);
        //存入SecurityContextHolder,要求存入authentication对象，使用UsernamePasswordAuthenticationToken制造authentication对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}